/**
 * js调用原生交互
 引用说明  window.jsbrige.callNative(<方法名>,<参数>,<返回值回掉函数>)；
 //
 window.jsbrige.callNative('getSAPrepareAttribute',"",function(data){
  alert(data);
})
 }
 *
 */
/* eslint-disable */
function JSBrige() {
  window.funcMap = new Map();
  this.callNative = function (nativeMethodName, argument, callback) {
    console.log("tag", "callNative");
    let argumentTmp = argument;
    if (typeof nativeMethodName !== "string") {
      throw new Error("Type of method must be string");
    }

    //Allowed types are Number, String, Date, Array,Object, and Null
    let type = typeof argument;
    let fliter = ["string", "number", "object", "null"];
    if (fliter.indexOf(type) === -1) {
      throw new Error("Type of argument must be number,string,object,and null");
    }

    if (type === "object") {
      argumentTmp = JSON.stringify(argument);
    }
    let call_id = nativeMethodName + Date.parse(new Date());
    if (callback != null && callback !== undefined) {
      funcMap[call_id] = callback;
    }

    // if (eval(`window.webkit.messageHandlers.BXGZAPP`) !== undefined) {
    let prames = {
      callAppMethod: nativeMethodName,
      callBackJsName: call_id,
      data: argument,
    };
    let pramesTmp = JSON.stringify(prames);
    BXGZAPP.postMessage(pramesTmp);
    // } else {
    //   throw new Error("Not in native environment");
    // }
  };

  /**
   *  callId 调用原生参数能取到
   */
  this.jsCallback = function (callId, params) {
    let callback = funcMap[callId];
    //method(params);
    if (callback != null && callback !== undefined) {
      callback(params);
    }
    funcMap.delete(callId);
  };
}
window.jsbrige = new JSBrige();
export default {
  // js调APP方法 （参数分别为:app提供的方法名  传给app的数据  回调）
  callNative(name, data, callback) {
    console.log("tag", "callHandler");
    window.jsbrige.callNative(name, data, callback);
  },
  // APP调js方法 （参数分别为:js提供的方法名  回调, data 带过来的参数）
  registerHandler(name, callback) {
    window.jsbrige[name] = (data) => {
      callback(data);
    };
  },
};
